package com.ruoyi.project.warehouse.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.information.domain.DataReportBean;
import com.ruoyi.project.inventory.domain.RyInventory;
import com.ruoyi.project.inventory.service.IRyInventoryService;
import com.ruoyi.project.warehouse.domain.*;
import com.ruoyi.project.warehouse.mapper.RyDepotRecordAuditMapper;
import com.ruoyi.project.warehouse.mapper.RyInventoryCurrentStockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.warehouse.mapper.RyDepotItemMapper;
import com.ruoyi.project.warehouse.service.IRyDepotItemService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入库Service业务层处理
 *
 * @author you
 * @date 2022-09-06
 */
@Service
public class RyDepotItemServiceImpl implements IRyDepotItemService
{
    @Autowired
    private RyDepotItemMapper ryDepotItemMapper;

    @Autowired
    private RyInventoryCurrentStockMapper ryInventoryCurrentStockMapper;

    @Autowired
    private IRyInventoryService ryInventoryService;

    @Autowired
    private RyDepotRecordAuditMapper ryDepotRecordAuditMapper;

    /**
     * 查询入库
     *
     * @param id 入库主键
     * @return 入库
     */
    @Override
    public RyDepotItem selectRyDepotItemById(Long id)
    {
        return ryDepotItemMapper.selectRyDepotItemById(id);
    }

    /**
     * 查询入库列表
     *
     * @param ryDepotItem 入库
     * @return 入库
     */
    @Override
    public List<RyDepotItemVo> selectRyDepotItemList(RyDepotItem ryDepotItem)
    {
        RyDepotRecordAudit ryDepotRecordAudit = new RyDepotRecordAudit();
        List<RyDepotItemVo> ryDepotItemVos = ryDepotItemMapper.selectRyDepotItemList(ryDepotItem);
        for (RyDepotItemVo ryDepotItemVo : ryDepotItemVos) {
            ryDepotItemVo.setStatus("0");
            //如果该入库记录是项目关联的，设置status为1
            if(ryDepotItemVo.getHeaderId()!=null){
                ryDepotItemVo.setStatus("1");
            }
            ryDepotRecordAudit.setDepotitemId(ryDepotItemVo.getId());
            ryDepotRecordAudit.setAuditStatus(0);
            //如果该入库记录正在审核中，设置status为1
            List<RyDepotRecordAuditVo> ryDepotRecordAuditVos = ryDepotRecordAuditMapper.selectRyDepotRecordAuditList(ryDepotRecordAudit);
            if(ryDepotRecordAuditVos.size()>0){
                ryDepotItemVo.setStatus("1");
            }
        }
        return ryDepotItemVos;
    }

    /**
     * 根据条件查询订单明细
     */
    public List<RyDepotItemVo> orderDetailList(DataReportBean dataReportBean){
        return ryDepotItemMapper.orderDetailList(dataReportBean);
    }

    /**
     * 根据仓库id和物品id查询锁定数量
      */
    public RyDepotItem getLockNumById(RyDepotItem ryDepotItem){
        return ryDepotItemMapper.getLockNumById(ryDepotItem);
    }

    /**
     * 根据仓库id和物品id查询已入库数量
     */
    public Long getNumByDepotInventoryId(RyDepotItem ryDepotItem){
        return ryDepotItemMapper.getNumByDepotInventoryId(ryDepotItem);
    }

    /**
     * 根据仓库id和物品id查询入库记录数
     */
    public int getCountByDepotInventoryId(RyDepotItem ryDepotItem){
        return ryDepotItemMapper.getCountByDepotInventoryId(ryDepotItem);
    }

    /**
     * 新增入库
     *
     * @param ryDepotItemVo 入库
     * @return 结果
     */
    @Override
    @Transactional
    public int insertRyDepotItem(RyDepotItemVo ryDepotItemVo)
    {
        //获取仓库id和商品id
        Long depotId = ryDepotItemVo.getDepotId();
        Long inventoryId = ryDepotItemVo.getInventoryId();
        RyInventoryCurrentStock paramstock = new RyInventoryCurrentStock();
        paramstock.setDepotId(depotId);
        paramstock.setInventoryId(inventoryId);
        /**
         * 根据仓库id和商品id查询仓库当前库存记录中是否存在此物品记录，
         * 1.存在的话就对当前量进行修改
         * 2.不存在则在仓库当前库存记录中新增此条记录
         * 3.不论仓库当前库存表中是否存在此记录，都需要在表单明细子表中新增此条入库记录
         */
        //查询是否存在
        RyInventoryCurrentStock result = ryInventoryCurrentStockMapper.getCurrentStockByDepotInventId(paramstock);
        System.out.println("--> result:"+result);

        //创建参数对象
        RyInventoryCurrentStock param = new RyInventoryCurrentStock();
        if(result != null){//存在此数据，执行修改
            //计算需要更改的总库数量
            //获取原库存数
            Double oldNum = result.getCurrentNumber();
            //获取新入库数量
            Double inNum = ryDepotItemVo.getOperNumber();
            //需要更改的数量
            Double updateNum = oldNum + inNum;
            param.setCurrentNumber(updateNum);

            //执行修改语句，根据id修改
            param.setId(result.getId());
            ryInventoryCurrentStockMapper.updateRyInventoryCurrentStock(param);
        } else {//不存在,执行新增
            param.setDepotId(ryDepotItemVo.getDepotId());
            param.setInventoryId(ryDepotItemVo.getInventoryId());
            param.setCurrentNumber(ryDepotItemVo.getOperNumber());

            //执行新增语句
            ryInventoryCurrentStockMapper.insertRyInventoryCurrentStock(param);
        }
        //入库记录新增
        RyDepotItem ryDepotItem = new RyDepotItem();
        ryDepotItem.setInventoryId(ryDepotItemVo.getInventoryId());
        ryDepotItem.setDepotId(ryDepotItemVo.getDepotId());
        ryDepotItem.setAllPrice(ryDepotItemVo.getAllPrice());
        ryDepotItem.setOperNumber(ryDepotItemVo.getOperNumber());
        ryDepotItem.setOperTime(DateUtils.getNowDate());
        ryDepotItem.setRemark(ryDepotItemVo.getRemark());
        ryDepotItem.setHeaderType("0");//0代表入库
        ryDepotItem.setUpdateTime(new Date());

        return ryDepotItemMapper.insertRyDepotItem(ryDepotItem);
    }

    /**
     * 库存入库导入
     */
    @Override
    @Transactional
    public AjaxResult dataImport(DataImport dataImport){
        if(dataImport.getDataList() == null || dataImport.getDataList().size() == 0){
            return AjaxResult.error("导入数据不能为空");
        }

        //创建未能导入数据列表
        List<InventoryImportBean> noImportList = new ArrayList<InventoryImportBean>();

        //仓库id
        Long depotId = 1L;
        //判断是总库导入和还是工具库导入
        if("0".equals(dataImport.getWarehouseType())){//1是总库
            depotId = 1L;
        } else if("1".equals(dataImport.getWarehouseType())) {//2是工具库
            depotId = 2L;
        }
        //物品id
        Long inventoryId = 0L;
        /**
         * 遍历导入的数据，
         * 1.根据物品名和规格查询物品信息表，如果物品存在则直接入总库修改库存
         * 2.如果不存在则先将此物品插入物品信息表中后修改总库库存
         */
        for(InventoryImportBean inventoryImportBean : dataImport.getDataList()){
            //获取总数量,去除空格
            String totalNumber = inventoryImportBean.getTotalNumber();
            if(StringUtils.isNotBlank(totalNumber)){
                totalNumber.replaceAll(" ", "");
            } else{
                totalNumber = "";
            }

            String brand = inventoryImportBean.getBrand();
            if(StringUtils.isNotBlank(brand)){
                brand.replaceAll(" ", "");
            }

            String kindCode = inventoryImportBean.getKindCode();
            if(StringUtils.isNotBlank(kindCode)){
                kindCode.replaceAll(" ", "");
            }
            String categoryCode = inventoryImportBean.getCategoryCode();
            if(StringUtils.isNotBlank(categoryCode)){
                categoryCode.replaceAll(" ", "");
            }
            String itemCode = inventoryImportBean.getItemCode();
            if(StringUtils.isNotBlank(itemCode)){
                itemCode.replaceAll(" ", "");
            }
            String unit = inventoryImportBean.getUnit();
            if(StringUtils.isNotBlank(unit)){
                unit.replaceAll(" ", "");
            }
            String remark = inventoryImportBean.getRemark();
            String location = inventoryImportBean.getLocation();

            //获取物品名和规格,并去除空格转为全大写
            String name = inventoryImportBean.getName();
            if(StringUtils.isNotBlank(name)){
                name.replaceAll(" ", "").toUpperCase();
            } else {
                noImportList.add(inventoryImportBean);
                continue;
            }

            String specifications = inventoryImportBean.getSpecifications();
            if(StringUtils.isNotBlank(specifications)){
                specifications.replaceAll(" ", "").toUpperCase();
            } else {
                noImportList.add(inventoryImportBean);
                continue;
            }

            //根据物品名和规格查询物品信息表
            RyInventory ryInventory = ryInventoryService.selectInfoByNameSpeci(specifications,name);
            if(ryInventory == null){//不存在
                ryInventory = new RyInventory();
                ryInventory.setName(name);
                ryInventory.setSpecifications(specifications);
                ryInventory.setBrand(brand);
                ryInventory.setKindCode(kindCode);//种类
                ryInventory.setCategoryCode(categoryCode);//品类
                ryInventory.setItemCode(itemCode);//项编码
                ryInventory.setWbs("" + kindCode + categoryCode + itemCode);//wbs
                ryInventory.setUnit(unit);//单位
                ryInventory.setRemark(remark);//备注
                ryInventory.setLocation(location);//库位

                //插入物品信息数据
                ryInventoryService.insertRyInventory(ryInventory);
            }
            //设置物品id
            inventoryId = ryInventory.getId();

            //判断数量是否是数字类型,包括整型和浮点型,不能判断带有“-”的负数和0(数量0入库没有意义)
            if(!totalNumber.matches("([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])")){//如果不是纯数字，则跳过并统计
                noImportList.add(inventoryImportBean);
                continue;
            }

            //修改仓库库存
            RyInventoryCurrentStock paramstock = new RyInventoryCurrentStock();
            paramstock.setDepotId(depotId);
            paramstock.setInventoryId(inventoryId);
            /**
             * 根据仓库id和商品id查询仓库当前库存记录中是否存在此物品记录，
             * 1.存在的话就对当前量进行修改
             * 2.不存在则在仓库当前库存记录中新增此条记录
             * 3.不论仓库当前库存表中是否存在此记录，都需要在表单明细子表中新增此条入库记录
             */
            //查询是否存在
            RyInventoryCurrentStock result = ryInventoryCurrentStockMapper.getCurrentStockByDepotInventId(paramstock);
            System.out.println("--> result:"+result);

            //创建参数对象
            RyInventoryCurrentStock param = new RyInventoryCurrentStock();
            if(result != null){//存在此数据，执行修改
                //计算需要更改的总库数量
                //获取原库存数
                Double oldNum = result.getCurrentNumber();
                //获取新入库数量
                Double inNum = Double.valueOf(totalNumber);
                //需要更改的数量
                Double updateNum = oldNum + inNum;
                param.setCurrentNumber(updateNum);

                //执行修改语句，根据id修改
                param.setId(result.getId());
                ryInventoryCurrentStockMapper.updateRyInventoryCurrentStock(param);
            } else {//不存在,执行新增
                param.setDepotId(depotId);
                param.setInventoryId(inventoryId);
                param.setCurrentNumber(Double.valueOf(totalNumber));

                //执行新增语句
                ryInventoryCurrentStockMapper.insertRyInventoryCurrentStock(param);
            }
            //入库记录新增
            RyDepotItem ryDepotItem = new RyDepotItem();
            ryDepotItem.setInventoryId(inventoryId);
            ryDepotItem.setDepotId(depotId);
            ryDepotItem.setOperNumber(Double.valueOf(totalNumber));
            ryDepotItem.setOperTime(DateUtils.getNowDate());
            ryDepotItem.setRemark(remark);
            ryDepotItem.setHeaderType("0");//0代表入库

            ryDepotItemMapper.insertRyDepotItem(ryDepotItem);
        }

        System.out.println("size:-->"+dataImport.getDataList().size()+"  |  " + noImportList.size());
        if(noImportList.size() == 0){
            return AjaxResult.success("全部导入成功");
        } else {
            return AjaxResult.success("导入部分成功,异常数据为 : " + noImportList.toString());
        }
    }

    /**
     * 批量删除入库
     *
     * @param ids 需要删除的入库主键
     * @return 结果
     */
    @Override
    public int deleteRyDepotItemByIds(Long[] ids)
    {
        return ryDepotItemMapper.deleteRyDepotItemByIds(ids);
    }

    /**
     * 删除入库信息
     *
     * @param id 入库主键
     * @return 结果
     */
    @Override
    public int deleteRyDepotItemById(Long id)
    {
        return ryDepotItemMapper.deleteRyDepotItemById(id);
    }
}
